<template>
    <div>
        <el-dialog
            width="70%"
            :title="!form.id ? '新增商品' : '编辑商品'"
            :visible.sync="visible"
            :close-on-click-modal="false"
            :before-close="beforeClose"
            @close="handleDialogClose">

            <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                <el-tabs class="spu_tabs" v-model="activeTab" type="card" :before-leave="beforeLeave">

                    <el-tab-pane label="基本信息" name="base">
                        <!-- SPU 基本信息 -->
                        <div class="step" ref="base_dialog_wrap">

                            <el-form-item label="商品名称" prop="name">
                                <el-input v-model="form.name" placeholder="" style="width: 80%;"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="商品分类" prop="cateId">
                                <CategoryCascader ref="category" :categoryPath.sync="categoryPath"></CategoryCascader>
                            </el-form-item>
                            <el-form-item label="商品品牌" prop="brandId">
                                <BrandSelect ref="brand" :selectBrandId.sync="selectBrandId"></BrandSelect>
                            </el-form-item> -->
                            <el-form-item label="商品主图" prop="headImg">
                                <SingleUpload v-model="form.headImg" listType="picture-card"></SingleUpload>
                                <i style="color: #ccc" class="mt10">尺寸：600x600</i>
                            </el-form-item>
                            <el-form-item label="视频介绍" prop="video">
                                <div style="width: 500px;">
                                    <SingleUpload v-model="form.video" listType="text"></SingleUpload>
                                    <i style="color: #ccc" class="mt10">详情页视频介绍</i>
                                </div>
                            </el-form-item>
                            <el-form-item label="商品轮播图" prop="imgs">
                                <MultiUpload v-model="imgs"></MultiUpload>
                                <i style="color: #ccc" class="mt10">尺寸：750x400</i>
                            </el-form-item>

                            <!-- <el-form-item label="快递运费" prop="freeShippingType">
                                <el-radio-group v-model="form.freeShippingType">
                                    <div class="freeShipping_wrap">
                                        <el-radio :label="1">
                                            包邮
                                        </el-radio>
                                        <el-radio :label="4">
                                            到付
                                        </el-radio>
                                        <el-radio :label="2">
                                            统一运费
                                            <el-input v-model="form.freeShipping" :disabled="form.freeShippingType!=2" placeholder="" style="width:130px" /> 元
                                        </el-radio>
                                        <el-radio :label="3">
                                            运费模板
                                            <el-input v-model="form.freeShippingTemplateId" :disabled="form.freeShippingType!=3" placeholder="" style="width:130px" />
                                        </el-radio>
                                    </div>
                                </el-radio-group>
                            </el-form-item> -->

                            <el-form-item label="库存预警" prop="stockWarn">
                                <el-input v-model="form.stockWarn" type="number" @input="numberic2(form,'stockWarn',$event)" style="width: 240px;"></el-input>
                            </el-form-item>

                            <el-form-item label="代理商" prop="agentIds">
                                <el-select v-model="form.agentIds" multiple :loading="loading" placeholder="请选择" filterable clearable style="width: 30%">
                                    <el-option
                                        v-for="item in agentList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                                <i> 根据SKU库存初始化代理商库存</i>
                            </el-form-item>

                            <!-- <el-form-item label="是否精品" prop="isBest">
                                <el-radio-group v-model="form.isBest">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="2">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否新品" prop="isNew">
                                <el-radio-group v-model="form.isNew">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="2">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否推荐" prop="isRecom">
                                <el-radio-group v-model="form.isRecom">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="2">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否热销产品" prop="isHot">
                                <el-radio-group v-model="form.isHot">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="2">否</el-radio>
                                </el-radio-group>
                            </el-form-item> -->
                            <el-form-item label="销售状态" prop="status">
                                <el-radio-group v-model="form.status">
                                    <el-radio :label="1">立即上架</el-radio>
                                    <el-radio :label="2">放入仓库</el-radio>
                                </el-radio-group>
                            </el-form-item>

                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="商品详情" name="detail">
                        <!-- 设置商品详情 -->
                        <div class="step" ref="detail_dialog_wrap">
                            <div id="decriptEditor"></div>
                        </div>
                    </el-tab-pane>

                    <!-- 设置规格属性 -->
                    <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  form.baseAttrs[0] = [{attrId:xx,val:}]-->
                    <!-- <el-tab-pane label="规格属性" name="attr">
                        <div class="step" ref="attr_dialog_wrap">

                            <el-card class="box-card"  v-if="attrGroups && attrGroups.length > 0">

                                <el-tabs tab-position="left" style="width:98%; margin-bottom: 20px">
                                    <el-tab-pane
                                    :label="group.attrGroupName"
                                    v-for="(group, gidx) in attrGroups"
                                    :key="group.attrGroupId">


                                        <el-form :model="form">
                                            <el-form-item v-for="(attr,aidx) in group.attrs" :key="attr.id">
                                                <div class="base_attr_wrap">
                                                    <div class="label">
                                                        {{attr.attrName}}
                                                    </div>
                                                    <div class="select_vals">
                                                        <el-select
                                                            v-model="dataResp.baseAttrs[gidx][aidx].attrValues"
                                                            :multiple="attr.valueType == 1"
                                                            filterable
                                                            allow-create
                                                            default-first-option
                                                            placeholder="请选择或输入值"
                                                            style="width: 100%">
                                                                <el-option
                                                                    v-for="(val,vidx) in attr.valueSelect.split(';')"
                                                                    :key="vidx"
                                                                    :label="val"
                                                                    :value="val">
                                                                </el-option>
                                                        </el-select>
                                                    </div>
                                                    <div class="show_desc">
                                                        <el-checkbox
                                                            v-model="dataResp.baseAttrs[gidx][aidx].showDesc"
                                                            :true-label="1"
                                                            :false-label="0"
                                                        >快速展示</el-checkbox>
                                                    </div>
                                                </div>
                                            </el-form-item>
                                        </el-form>
                                        <el-button type="primary">添加属性</el-button>
                                    </el-tab-pane>
                                </el-tabs>

                            </el-card>

                            <el-alert v-else title="提示" type="warning" description="该商品分类，无规格参数信息" show-icon />
                        </div>
                    </el-tab-pane> -->

                    <el-tab-pane label="SKU信息" name="sku">
                        <!-- 设置SKU信息，并保存商品信息 -->
                        <div class="step" ref="sku_dialog_wrap">
                            <el-card shadow="hover" ref="content_card">
                                <el-radio-group v-model="form.specType" style="margin: 8px 0;">
                                    <el-radio :label="1">统一规格</el-radio>
                                    <el-radio :label="2">多规格</el-radio>
                                </el-radio-group>
                                <el-button v-if="form.specType == 2" style="margin-left:20px" @click="handleAddSaleAttr" type="primary" size="mini" icon="el-icon-plus">添加规格</el-button>
                            </el-card>

                            <!-- 统一规格 -->
                            <el-card shadow="hover" ref="content_card" class="mt10" v-show="form.specType == 1">
                                <el-table :data="skus1" fit border class="mt10">
                                    <el-table-column label="规格图片" width="100" align="center">
                                        <template slot-scope="scope">
                                            <div class="skuImg">
                                                <SingleUpload v-model="scope.row.skuImg" listType="picture-card"></SingleUpload>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="SKU名称">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.skuName"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="销售价(元)" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.salePrice"></el-input>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column label="成本价(元)" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.costPrice"></el-input>
                                        </template>
                                    </el-table-column> -->
                                    <el-table-column label="市场价(元)" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.marketPrice"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.stockNum"></el-input>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column label="条码" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.barcode"></el-input>
                                        </template>
                                    </el-table-column> -->
                                </el-table>

                            </el-card>

                            <!-- 多规格 -->
                            <el-card shadow="hover" ref="content_card" class="mt10" v-show="form.specType == 2">

                                <el-divider content-position="left"><b>销售规格</b></el-divider>
                                <!-- 销售规格设置 -->
                                <el-table :data="tableSaleAttrs" fit :border="false" :show-header="false" empty-text="暂无数据，请添加规格">
                                    <el-table-column label="规格项" width="200px">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.attrName" size="medium" @blur="generateSkus"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="规格值">
                                        <template slot-scope="scope">
                                            <el-checkbox-group v-model="tableSaleAttrs[scope.$index].attrValues" @change="generateSkus">

                                                <template v-if="tableSaleAttrs[scope.$index].valueSelect">
                                                    <el-checkbox
                                                    :label="val"
                                                    v-for="val in tableSaleAttrs[scope.$index].valueSelect.split(';')"
                                                    :key="val"
                                                    style="margin-right: 20px;"
                                                    ></el-checkbox>
                                                </template>

                                                <div style="display:inline">
                                                    <el-button
                                                        v-show="!inputVisible[scope.$index].view"
                                                        class="button-new-tag"
                                                        size="medium"
                                                        icon="el-icon-plus"
                                                        @click="showInput(scope.$index)">自定义</el-button>
                                                    <el-input
                                                        v-show="inputVisible[scope.$index].view"
                                                        v-model="inputValue[scope.$index].val"
                                                        :ref="`SpecInputValue`"
                                                        size="medium"
                                                        style="width:150px"
                                                        @keyup.enter.native="handleInputConfirm(scope.$index)"
                                                        @blur="handleInputConfirm(scope.$index)"
                                                    ></el-input>
                                                </div>
                                            </el-checkbox-group>
                                        </template>
                                    </el-table-column>
                                </el-table>

                                <el-divider content-position="left"><b>SKU列表</b></el-divider>

                                <div class="batch" v-if="form.specType == 2 && skus2 && skus2.length > 0">
                                    <el-input placeholder="SKU名称" v-model="batch.skuName" style="width: 250px;"></el-input>
                                    <el-input placeholder="销售价(元)" type="number" v-model="batch.salePrice" @input="numberic(batch, 'salePrice', $event)" style="width: 100px;margin-left:10px"></el-input>
                                    <!-- <el-input placeholder="成本价(元)" type="number" v-model="batch.costPrice" @input="numberic(batch, 'costPrice', $event)" style="width: 100px;margin-left:10px"></el-input> -->
                                    <el-input placeholder="市场价(元)" type="number" v-model="batch.marketPrice" @input="numberic(batch, 'marketPrice', $event)" style="width: 100px;margin-left:10px"></el-input>
                                    <el-input placeholder="库存量" type="number" v-model="batch.stockNum" @input="numberic2(batch, 'stockNum', $event)" style="width: 100px;margin-left:10px"></el-input>
                                    <el-input placeholder="条形码" v-model="batch.barcode" style="width: 150px;margin-left:10px"></el-input>
                                    <el-button @click="handleBatchInput" type="primary" style="margin-left:10px">批量设置</el-button>
                                </div>

                                <!-- SKU销售数据组合 -->
                                <el-table :data="skus2" height="500" fit border class="mt10" empty-text="暂无数据，请先添加销售规格">

                                    <el-table-column :label="`属性组合 （${skus2?skus2.length:0}个SKU）`">
                                        <el-table-column
                                            :label="item.attrName"
                                            v-for="(item, index) in skuAttrTableColumn"
                                            :key="index"
                                        >
                                            <template slot-scope="scope" v-if="scope.row.specAttrs[index]">
                                                <span style="margin-left: 10px">{{
                                                    scope.row.specAttrs[index].attrValue
                                                }}</span>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>

                                    <el-table-column label="规格图片" width="100" align="center">
                                        <template slot-scope="scope">
                                            <div class="skuImg">
                                                <SingleUpload v-model="scope.row.skuImg" listType="picture-card"></SingleUpload>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="SKU名称" width="200">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.skuName"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="销售价(元)" width="120">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.salePrice" type="number" @input="numberic(scope.row,'salePrice',$event)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column label="成本价(元)" width="120">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.costPrice" type="number" @input="numberic(scope.row,'costPrice',$event)"></el-input>
                                        </template>
                                    </el-table-column> -->
                                    <el-table-column label="市场价(元)" width="120">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.marketPrice" type="number" @input="numberic(scope.row,'marketPrice',$event)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" width="100">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.stockNum" type="number" @input="numberic2(scope.row,'stockNum',$event)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column label="条码" width="150">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.barcode"></el-input>
                                        </template>
                                    </el-table-column> -->

                                </el-table>

                            </el-card>

                        </div>
                    </el-tab-pane>

                    <!-- 分销设置 -->
                    <!-- <el-tab-pane label="分销设置" name="commission">
                        <div class="step" ref="commission_dialog_wrap">

                            <el-form-item label="分销佣金" prop="isCommission">
                                <el-radio-group v-model="form.isCommission">
                                    <el-radio :label="1">开启</el-radio>
                                    <el-radio :label="2">不开启</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="一级分销比例" prop="firstRatio">
                                <el-input v-model="form.firstRatio" :disabled="form.isCommission==2" placeholder="1~100" type="number" @input="numberic100(form,'firstRatio',$event)" style="width:200px"></el-input>
                            </el-form-item>
                            <el-form-item label="二级分销比例" prop="secondRatio">
                                <el-input v-model="form.secondRatio" :disabled="form.isCommission==2" placeholder="1~100" type="number" @input="numberic100(form,'secondRatio',$event)" style="width:200px"></el-input>
                            </el-form-item>
                            <el-form-item label="三级分销比例" prop="threeRatio">
                                <el-input v-model="form.threeRatio" :disabled="form.isCommission==2" placeholder="1~100" type="number" @input="numberic100(form,'threeRatio',$event)" style="width:200px"></el-input>
                            </el-form-item>

                        </div>
                    </el-tab-pane> -->

                </el-tabs>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button @click="handleSubmit()" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>

        </el-dialog>
    </div>
</template>

<script>
// import CategoryCascader from "@/views/mall/pmscategory/components/category-cascader";
// import BrandSelect from "@/views/mall/pmsbrand/components/brand-select";
import SingleUpload from '@/views/components/upload/single-upload'
import MultiUpload from "@/views/components/oss/upload/MultipartUpload";
import E from "wangeditor";
import Config from '@/config'
var OSS = require('ali-oss');
import { getUUID, numberic, numberic2, numberic100 } from "@/libs";

export default {
    components: {
        // CategoryCascader,
        // BrandSelect,
        SingleUpload,
        MultiUpload
    },
    data() {
        return {
            visible: false,
            // catePathSub: null,
            // brandIdSub: null,
            activeTab: 'base',
            submitLoading: false,
            loading: false,
            form: {
                name: null,
                headImg: null,
                agentIds: null,
                cateId: null,
                brandId: null,
                imgs: [],
                decript: null,
                video: null,
                isBest: 2,
                isHot: 2,
                isNew: 2,
                isRecom: 2,
                isCommission: 2,
                firstRatio: null,
                secondRatio: null,
                threeRatio: null,
                stockWarn: null,
                freeShippingType: 1,
                freeShipping: null,
                freeShippingTemplateId: null,
                status: 1,
                specType: 1,        // 规格类型：1->统一规格，2->多规格
                // baseAttrs: [],      // 基本属性
                skus: [],           // 所有sku信息
                spuAttrValues: []   // 服务器返回的基本规格属性
            },
            rules: {
                cateId: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '商品名称不能为空', trigger: 'blur' }
                ]
            },
            // 商品轮播图
            imgs: [],

            // categoryPath: [],
            // selectBrandId: null,

            clinet: null,
            decriptEditor: null,
            decriptContent: null,

            // 属性分组
            // attrGroups: [],
            // dataResp: {
            //     baseAttrs: [],
            // },

            // 规格设置
            tableSaleAttrs: [],
            inputVisible: [],
            inputValue: [],

            // 销售属性
            cateSaleAttrs: [],

            // SKU 销售属性表格头
            skuAttrTableColumn: [],

            // 统一规格
            skus1: [{
                // SKU基本信息
                skuName: null,
                skuImg: null,
                salePrice: 0,
                marketPrice: 0,
                // costPrice: 0,
                stockNum: 0,
                // barcode: null
            }],
            // 多规格
            skus2: [],

            // 批量设置价格参数
            batch: {
                skuName: null,
                salePrice: null,
                marketPrice: null,
                // costPrice: 0,
                stockNum: null,
                // barcode: null
            },

            agentList: [],

            numberic,
            numberic2,
            numberic100
        }
    },

    watch: {
        activeTab(val) {
            this.$refs.base_dialog_wrap.scrollTo(0,0);
            // this.$refs.detail_dialog_wrap.scrollTo(0,0);
            // this.$refs.attr_dialog_wrap.scrollTo(0,0);
            // this.$refs.sku_dialog_wrap.scrollTo(0,0);
            // this.$refs.commission_dialog_wrap.scrollTo(0,0);
        }
    },

    methods: {

        init(id) {
            const refs = this.$refs
            this.activeTab = 'base'

            this.form.id = id || null
            this.visible = true

            this.getAgentist()

            this.$nextTick(() => {
                this.$refs.base_dialog_wrap.scrollTo(0,0);
                refs['form'].resetFields()

                this.initEditor()

                // // 订阅消息，当分类级联发生变动，级联组件发布订阅消息，获取分类ID
                // this.catePathSub = PubSub.subscribe("catePathId", (msg, val) => {
                //     if(val.length > 0) {
                //         this.form.cateId = val[val.length - 1];
                //     }
                // });
                // // 订阅消息，品牌组件发布订阅消息，获取品牌ID
                // this.brandIdSub = PubSub.subscribe("brandId", (msg, val) => {
                //     this.form.brandId = val;
                // });

                if(this.form.id) {
                    this.getInfo(this.form.id)
                }


                // 测试SKU用的数据
                // let attrs = [
                //     {
                //         attrId: 0,
                //         attrName: '颜色',
                //         attrValues: [],
                //         valueSelect: "白色;红色;蓝色"
                //     },
                //     {
                //         attrId: 1,
                //         attrName: '内存',
                //         attrValues: [],
                //         valueSelect: "8G;16G;32G"
                //     }
                // ]
                // this.tableSaleAttrs = attrs
                // this.inputVisible = [{ view: false }, { view: false }];
                // this.inputValue = [{ val: "" }, { val: "" }];
            })
        },


        /**
         * tab切换前检查是否添加基本信息
         */
        beforeLeave(activeName, oldActiveName) {
            var p = new Promise((resolve, reject) => {
                if(activeName !== 'base') {
                    this.$refs.form.validate(valid => {
                        if (valid) {
                            // 初始化规格属性
                            // this.showBaseAttrs()
                            resolve()
                        } else {
                            this.$notify({ title: '提示', message: '请先填写基本信息', type: 'info' });
                            reject(err)
                        }
                    });
                } else {
                    resolve()
                }
            })
            return p
        },


        /**
         * 根据分类获取规格属性
         */
        // async showBaseAttrs() {
        //     const res = await this.$http({
        //         url: `/mall/pmsattrgroup/${this.form.cateId}/withattr`,
        //         method: 'GET'
        //     })
        //     if (this.ResultMessage(res, false)) {
        //         let list = res.data

        //         if(list && list.length > 0) {
        //             //先对表单的baseAttrs进行初始化
        //             list.forEach(item => {
        //                 let attrArray = [];

        //                 if(item.attrs) {
        //                     item.attrs.forEach(attr => {
        //                         if(this.form.spuAttrValues && this.form.spuAttrValues.length > 0) {
        //                             // 回填基本规格属性
        //                             let val = this.form.spuAttrValues.filter(item => item.attrId == attr.id)
        //                             if(val && val.length > 0) {
        //                                 const baseAttr = val[0]
        //                                 attrArray.push({
        //                                     attrId: attr.id,
        //                                     attrValues: baseAttr.valueType == 0 ? baseAttr.attrValue : baseAttr.attrValue.split(';'),
        //                                     showDesc: attr.showDesc
        //                                 });
        //                             } else {
        //                                 attrArray.push({
        //                                     attrId: attr.id,
        //                                     attrValues: "",
        //                                     showDesc: attr.showDesc
        //                                 });
        //                             }
        //                         } else {
        //                             attrArray.push({
        //                                 attrId: attr.id,
        //                                 attrValues: "",
        //                                 showDesc: attr.showDesc
        //                             });
        //                         }
        //                     });
        //                     this.dataResp.baseAttrs.push(attrArray);
        //                 } else {
        //                     this.dataResp.baseAttrs.push([]);
        //                 }
        //             });
        //             this.attrGroups = list;

        //         } else {
        //             this.dataResp.baseAttrs = []
        //             this.attrGroups = []
        //         }
        //     }
        // },

        /**
         * 根据分类获取销售属性
         */
        /*async showSaleAttrs(){
            const res = await this.$http({
                url: `/mall/pmsattr/sale/list`,
                method: 'GET',
                params: {page:1, limit: 1000, cateId: this.form.cateId}
            })
            if (this.ResultMessage(res, false)) {
                this.cateSaleAttrs = res.data.records || []
                console.log(this.cateSaleAttrs);

                let attrs = []
                this.cateSaleAttrs.forEach((item, index) => {
                    attrs.push(
                        {
                            attrId: index,
                            attrName: item.attrName,
                            attrValues: [],
                            valueSelect: item.valueSelect
                        }
                    )
                    this.inputVisible.push({ view: false });
                    this.inputValue.push({ val: "" });
                })

                // 如果 this.form.id 有值说明是编辑商品，已有销售属性
                // 将分类下的销售属性合并到已有的销售属性上
                if(this.form.id) {
                    attrs.forEach((item, index) => {
                        this.tableSaleAttrs.forEach(cur => {
                            if(cur.attrName == item.attrName) {
                                let curVals = cur.valueSelect.split(';')
                                let itemVals = item.valueSelect.split(';')
                                let arr = Array.from(new Set([...curVals, ...itemVals]))
                                cur.valueSelect = arr.join(';')
                            }
                        })
                    })
                    // 未解决好，换类别需要情况sku，暂时全部收到添加sku销售属性
                    if(this.tableSaleAttrs && this.tableSaleAttrs.length == 0) {
                        this.tableSaleAttrs = attrs
                    }
                } else {
                    console.log('====',attrs);
                    this.tableSaleAttrs = attrs
                }

            }
        },*/

        /**
         * 把页面绑定的所有“规格属性”处理到form的baseAttr里
         */
        generateSaleAttrs() {
            this.form.baseAttrs = [];
            this.dataResp.baseAttrs.forEach(item => {
                item.forEach(attr => {
                    let { attrId, attrValues, showDesc } = attr;
                    //跳过没有录入值的属性
                    if (attrValues != "") {
                        if (attrValues instanceof Array) {
                            //多个值用;隔开
                            attrValues = attrValues.join(";");
                        }
                        this.form.baseAttrs.push({ attrId, attrValues, showDesc });
                    }
                });
            });
        },

        /**
         * 完成SKU相关设置
         * ---------------------
         * SKU销售规格相关设置
         */
        handleAddSaleAttr() {
            let attr = {
                attrId: null,
                attrName: null,
                attrValues: [],
                valueSelect: ''
            }
            this.tableSaleAttrs.push(attr)
            this.tableSaleAttrs.forEach((item, index) => item.attrId = index)
            this.inputVisible.push({ view: false });
            this.inputValue.push({ val: "" });
        },
        showInput(idx) {
            this.inputVisible[idx].view = true;
            this.$nextTick(() => this.$refs.SpecInputValue.focus());
        },
        handleInputConfirm(idx) {
            let inputValue = this.inputValue[idx].val;
            if (inputValue) {
                if (!this.tableSaleAttrs[idx].valueSelect || this.tableSaleAttrs[idx].valueSelect == "") {
                    this.tableSaleAttrs[idx].valueSelect = inputValue;
                } else {
                    this.tableSaleAttrs[idx].valueSelect += ";" + inputValue;
                }
            }
            this.inputVisible[idx].view = false;
            this.inputValue[idx].val = "";
        },

        /**
         * 生成SKU信息
         */
        generateSkus() {
            // 选中的规格
            let selectValues = [];
            // SKU销售属性的列名称
            this.skuAttrTableColumn = []

            this.tableSaleAttrs.forEach(item => {
                if(item.attrName && item.attrValues.length > 0) {
                    // 收集销售属性值，进行笛卡尔积运算生成SKU组合
                    selectValues.push(item.attrValues);
                    // 销售属性列名称
                    this.skuAttrTableColumn.push(item);
                }
            });

            //根据笛卡尔积运算进行生成sku组合
            let descartes = this.descartes(selectValues);
            // console.log("SKU生成的组合", JSON.stringify(descartes));

            //有多少descartes就有多少sku
            let skus = [];
            descartes.forEach((descar, descaridx) => {
                let attrArray = []; //sku属性组

                descar.forEach((de, index) => {
                    //构造saleAttr信息
                    let saleAttrItem = {
                        attrId: this.skuAttrTableColumn[index].attrId,
                        attrName: this.skuAttrTableColumn[index].attrName,
                        attrValue: de
                    };
                    attrArray.push(saleAttrItem);
                });

                // 判断如果之前有就用之前的值;
                let res = this.hasAndReturnSku(this.skus2, descar);

                if (res === null) {
                    skus.push({
                        // 销售属性
                        specAttrs: attrArray,
                        // 销售规格
                        specDescar: descar,
                        // SKU基本信息
                        skuName: this.form.name + " " + descar.join(" "),
                        skuImg: null,
                        salePrice: 0,
                        marketPrice: 0,
                        // costPrice: 0,
                        stockNum: 0,
                        // barcode: null
                    });
                } else {
                    skus.push(res);
                }

            })

            // SKU销售属性组合列表
            this.skus2 = skus;
        },

        /**
         * 回填SKU销售规格信息
         */
        handleSkuAttr(skus) {
            let map = new Map();
            skus.forEach((item, index) => {
                if(item.specAttrs) {
                    item.specAttrs.forEach(ia => {
                        let val = map.get(ia.attrName);
                        if(val) {
                            let vals = val.split(';')
                            if(vals.indexOf(ia.attrValue) == -1) {
                                map.set(ia.attrName, vals.join(';') + ';' + ia.attrValue)
                            }
                        } else {
                            map.set(ia.attrName, ia.attrValue)
                        }
                    })
                }
            })

            let attrs = []
            map.forEach((value, key, Map) => {
                attrs.push(
                    {
                        attrId: 0,
                        attrName: key,
                        attrValues: value.split(';'),
                        valueSelect: value
                    }
                )
                this.inputVisible.push({ view: false });
                this.inputValue.push({ val: "" });
            })
            this.tableSaleAttrs = attrs
            this.generateSkus()
        },

        /**
         * 提交表单
         */
        async handleSubmit() {
            const refs = this.$refs
            this.submitLoading = true
            const valid = await refs['form'].validate().catch(() => {})
            if(valid) {

                // 把页面绑定的所有“规格属性”处理到form的baseAttr里
                // this.generateSaleAttrs()

                // 商品轮播图
                if(this.imgs) {
                    let imgList = []
                    this.imgs.forEach((item, index) => {
                        imgList.push({imgName: item.name, imgUrl: item.url})
                    })
                    this.form.imgs = imgList
                }

                // 统一规格
                if(this.form.specType == 1) {
                    this.form.skus = this.skus1
                } else {
                    // 多规格
                    this.form.skus = this.skus2
                }

                const confirm = await this.$confirm('将要提交商品数据，需要一小段时间，是否继续?', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: `/mall/pmsspu/${!this.form.id ? 'saveGoodsInfo' : 'updateGoodsInfo'}`,
                        method: 'POST',
                        data: this.form
                    })
                    if (this.ResultMessage(res)) {
                        // 调用父组件方法，刷新商品数量
                        this.$emit('getGoodsCount')
                        this.$emit('refreshDataList', true)
                        this.visible = false
                        this.submitLoading = false
                    } else {
                        this.submitLoading = false
                    }
                }
            } else {
                this.submitLoading = false
            }
        },

        /**
         * 获取SPU详细信息
         */
        async getInfo(id) {
            if (id) {
                const res = await this.$http({
                    url: '/mall/pmsspu/getGoodsInfo/',
                    method: 'GET',
                    params: {id}
                })
                this.form = Object.assign({}, res.data, {agentIds: null})

                // this.categoryPath = this.form.categoryPath
                // this.selectBrandId = this.form.brandId

                this.decriptEditor.txt.html(this.form.decript)

                this.form.imgs.forEach((item, index) => {
                    this.imgs.push({name: item.imgName, url: item.imgUrl})
                })

                // this.showBaseAttrs()

                // 统一规格
                if(this.form.specType == 1) {
                    console.log(this.form.skus);
                    if(this.form.skus) {
                        this.skus1 = this.form.skus
                    }
                    this.handleSkuAttr(this.skus1)
                } else {
                    // 多规格
                    this.form.skus.forEach((item, index) => {
                        let attrs = JSON.parse(item.attrs)
                        let descar = JSON.parse(item.descar)
                        item['specAttrs'] = attrs
                        item['specDescar'] = descar
                    })

                     // 初始化销售规格
                    this.skus2 = this.form.skus
                    this.handleSkuAttr(this.form.skus)

                    // 批量设置：初始化skuName
                    this.batch.skuName = this.form.title
                }
            }
        },

        /**
         * 批量设置
         */
        handleBatchInput() {
            this.skus2.forEach(item => {
                item.skuName = this.batch.skuName ? this.batch.skuName : item.skuName
                item.salePrice = this.batch.salePrice ? this.batch.salePrice : item.salePrice
                // item.costPrice = this.batch.costPrice ? this.batch.costPrice : item.costPrice
                item.marketPrice = this.batch.marketPrice ? this.batch.marketPrice : item.marketPrice
                item.stockNum = this.batch.stockNum ? this.batch.stockNum : item.stockNum
                // item.barcode = this.batch.barcode ? this.batch.barcode : item.barcode
            })
        },

        /**
         * 笛卡尔积运算，生成SKU销售组合
         */
        descartes(list) {
            //parent上一级索引;count指针计数
            var point = {};

            var result = [];
            var pIndex = null;
            var tempCount = 0;
            var temp = [];

            //根据参数列生成指针对象
            for (var index in list) {
                if (typeof list[index] == "object") {
                    point[index] = { parent: pIndex, count: 0 };
                    pIndex = index;
                }
            }

            //单维度数据结构直接返回
            if (pIndex == null) {
                return list;
            }

            //动态生成笛卡尔积
            while (true) {
                for (var index in list) {
                    tempCount = point[index]["count"];
                    temp.push(list[index][tempCount]);
                }

                //压入结果数组
                result.push(temp);
                temp = [];

                //检查指针最大值问题
                while (true) {
                    if (point[index]["count"] + 1 >= list[index].length) {
                        point[index]["count"] = 0;
                        pIndex = point[index]["parent"];
                        if (pIndex == null) {
                            return result;
                        }

                        //赋值parent进行再次检查
                        index = pIndex;
                    } else {
                        point[index]["count"]++;
                        break;
                    }
                }
            }
        },

        /**
         * 判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
         */
        hasAndReturnSku(skus, descar) {
            let res = null;
            if (skus && skus.length > 0) {
                for (let i = 0; i < skus.length; i++) {
                    if(skus[i].specDescar) {
                        if (skus[i].specDescar.join(" ") == descar.join(" ")) {
                            res = skus[i];
                        }
                    }
                }
            }
            return res;
        },

        /**
         * 获取代理商
         */
        async getAgentist() {
            this.loading = true
            const res = await this.$http({
                url: '/mall/wmsagentinfo/list',
                method: 'GET'
            })
            if (this.ResultMessage(res, false)) {
                this.agentList = res.data || []
            }
            this.loading = false
        },

        /**
         * 初始化编辑器
         */
        async initEditor() {
            const _this = this
            // 初始化阿里云OSS
            this.clinet = new OSS(Config.Aliyun.oss);

            const decriptEditor = new E('#decriptEditor')
            decriptEditor.config.showFullScreen = false
            decriptEditor.config.height = 360
            decriptEditor.config.zIndex = 1
            decriptEditor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
            decriptEditor.config.uploadVideoAccept = ['mp4']

            // 自定义上传图片
            decriptEditor.config.customUploadImg = async function (resultFiles, insertImgFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertImgFn)

                _this.loading.close()
            }
            // 自定义上传视频
            decriptEditor.config.customUploadVideo = async function (resultFiles, insertVideoFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertVideoFn)

                _this.loading.close()
            }
            // 配置 onchange 回调函数，将数据同步到 vue 中
            decriptEditor.config.onchange = (newHtml) => {
                _this.form.decript = newHtml
            }
            decriptEditor.create()

            this.decriptEditor = decriptEditor
        },
        /**
         * 上传到阿里云OSS
         */
        async handleUpload(resultFiles, insert) {
            const _this = this
            for(const file of resultFiles) {
                try {
                    let result = await this.clinet.multipartUpload(getUUID(), file, {
                        progress(p, checkpoint) {
                            // console.log('Object的上传进度', p);
                            // console.log('分片上传的断点信息', checkpoint);
                            _this.progress = p
                        }
                    })
                    const url = result.res.requestUrls[0].split('?')[0]
                    insert(url)
                } catch(err) {
                    console.log(err);
                }
            }
        },

        beforeClose(done) {
            // 调用销毁 API 对当前编辑器实例进行销毁
            if(this.decriptEditor) {
                this.decriptEditor.destroy()
                this.decriptEditor = null
            }
            done()
        },

        /**
         * 表单窗口关闭
         */
        handleDialogClose() {
            this.$refs.form.resetFields()

            // 商品轮播图
            this.imgs = []

            // this.categoryPath = []
            // this.selectBrandId = null

            // 属性分组
            // this.attrGroups = []
            // this.dataResp = {
            //     baseAttrs: []
            // }

            // 规格设置
            this.tableSaleAttrs = []
            this.inputVisible = []
            this.inputValue = []

            // SKU 销售属性表格头
            this.skuAttrTableColumn = []

            // 统一规格
            this.skus1 = [{
                // SKU基本信息
                skuName: null,
                skuImg: null,
                salePrice: 0,
                marketPrice: 0,
                // costPrice: 0,
                stockNum: 0,
                // barcode: null
            }],
            // 多规格
            this.skus2 = []

            // 批量设置价格参数
            this.batch = {
                skuName: null,
                salePrice: null,
                marketPrice: null,
                // costPrice: null,
                stockNum: null,
                // barcode: null
            }


        },
    },

    beforeDestroy() {
        // 调用销毁 API 对当前编辑器实例进行销毁
        if(this.decriptEditor) {
            this.decriptEditor.destroy()
            this.decriptEditor = null
        }
    }
}
</script>
<style lang="scss">
.spu_tabs{
    .el-tabs__header{
        margin: 0;
    }
}
.skuImg{
    display: flex;
    justify-content: center;
    align-items: center;
    .el-upload--picture-card{
        width: 60px;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .el-upload-list--picture-card .el-upload-list__item{
        margin: 0;
        width: 60px;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .disabled .el-upload--picture-card, .disabled .el-upload--picture{
        display: none;
    }
}
</style>
<style lang="scss" scoped>

.step{
    height: 450px;
    overflow-x: auto;
    padding-top: 10px;
}
.success {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 100px 0;
    i{
        font-size: 100px;
        color: #67C23A;
        margin-bottom: 20px;
        margin-bottom: 100px;
    }
}

.batch{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.base_attr_wrap{
    display: flex;
    .label{
        flex: 1;
    }
    .select_vals {
        display: flex;
        justify-content: flex-start;
        flex: 5;

    }
    .show_desc {
        display: flex;
        justify-content: flex-start;
        flex: 1;
        margin-left: 10px;
    }
}

.freeShipping_wrap{
    display: flex;
    flex-direction: column;

    &:first-child {
        margin-top: 13px;
    }

    .el-radio{
        margin-bottom: 10px;

        .el-input{
            margin-left: 20px;
            margin-right: 10px;
        }
    }
}
</style>
